import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Card,  Form, Button, Tooltip, Modal, Spin, Input, message} from 'antd';
import HeaderTab from '@/components/HeaderTab';
import Preview from './preview';
import styles from './index.less';
import InputText from '@/components/Input/index';
import { rule } from '../../../../node_modules/postcss';

let wait = 60;
@Form.create()
class Pagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      signName: {},
      visible: false,
      start: false,
      showError: false,
      phoneValue: '',
      loading: true,
      name: null,
      tabs: [{
        title: '手机短信',
        key: `/${window.storeId}/sms`,
      }, {
        title: '充值记录',
        key:  `/${window.storeId}/sms/buyrecord`
      },{
        title: '短信签名',
        key:  `/${window.storeId}/sms/sign`
      }]
    };
  }
  componentWillMount(){
    this.requestSignName(); 
    window.Isoption = false;         
  }

  componentDidMount() {
    window.Isoption = true;
  }

  requestSignName =() => {
    const { dispatch} = this.props;
    dispatch({
        type: 'stortMessage/GetSmsSignName',
        callBack: {
            success: res => {
                this.setState({
                    signName: res.Data,
                    name: res.Data.SignName,
                    loading: false
                })
            },
            error: res => {
                console.log(res.Msg)
            }
        }
    })
  }

  requestSendTestMsg =() => {
    const { dispatch} = this.props;
    const {phoneValue, name} = this.state;
    dispatch({
        type: 'stortMessage/SendTestMsg',
        payload: {
            SignName: name,
            Phone: phoneValue
        },
        callBack: {
            success: res => {
                if(res.Code ===0) {
                    message.success('发送成功')
                }
            },
            error: res => {
                message.error(res.Msg)
            }
        }
    })
  }

  onTextChange = (v) => {
    this.setState({ name: v.target.value  });
}

  onChange = (data)=> {
    this.setState({
      current: data.current,
      pageSize: data.pageSize,
    });
  }
  onTabChange=(id)=> {
    this.setState({
      activeId: id
    },()=>{
        router.replace({
            pathname: `${id}`
        })
    });
  }

  showModal = () => {
    this.setState({
      visible: true,
    });
  }

  handleOk = (e) => {
    const { dispatch} = this.props;
    const { name } = this.state;
    this.props.form.validateFields((err, values) => {
        if(!err) {
            dispatch({
                type: 'stortMessage/ChangeSignName',
                payload: {
                    SignName: name
                },
                callBack: {
                    success: res => {
                        if(res.Code ===0) {
                            message.success('修改成功');
                                this.setState({
                                    visible: false,
                                });
                           this.requestSignName();   
                        }
                    },
                    error: res => {
                        message.error(res.Msg)
                    }
                }
            })
        }
    })
  }

  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  }

  // 定时器
  time =() => {
    if(wait ===0) {
        this.setState({
            start: false
        })
        wait = 60;
    } else {
        this.setState({
            start: true
        })
        wait--;
        setTimeout(() => {
            this.time()
        }, 1000)
      }
  }

  // 发送短信
  clickSedText =() => {
      const {phoneValue} = this.state;
      let regl = /^1(3|4|5|7|8)\d{9}$/;
      if(regl.test(phoneValue)) {
        this.setState({
            showError: false
        })
        this.time();
        this.requestSendTestMsg();
      } else {
        this.setState({
            showError: true
        })
      }
  }

  // 手机号
  inputValueChange =(e) => {
    this.setState({
        phoneValue: e.target.value 
    })
  }

  renderEdit(signName) {
    if(signName.IsCommercial){
        if(signName.Status) {
            return (
                <Button type="primary" onClick={this.showModal}>
                    修改
                </Button>
            )
        } else {
            return (
                <Tooltip placement="right" title="本月已修改3次，下个月才能修改">
                    <Button>修改</Button>
                </Tooltip>
            )
        }
    }else {    
        return (
            <Tooltip placement="right" title="试用店铺不可修改">
                <Button>修改</Button>
            </Tooltip>
        )
    } 
  }

  render() {
    const {form: { getFieldDecorator },oemInfo, loading2} = this.props;
    const formItemLayout ={
        labelCol: {span: 6},
        wrapperCol: { span: 14},
    }
    const {signName, visible, start, showError, loading} = this.state;
    return (
        <Fragment>
        
            <Spin spinning={loading}>
                <Card bordered={false}>                          
                    <div className={styles.autoContent}>
                        <Preview title="短信" oemInfo={oemInfo} signName={signName.SignName}/>                 
                        <div className={styles.rightBox}>
                            <div className={styles.alert}>
                                <div>注意事项：</div>
                                <p>1. 建议使用你的店铺名或品牌名，使用其他签名可能短信审核不会通过；</p>
                                <p>2. 若签名内容侵犯到第三方权益必须获得第三方真实授权；</p>
                                <p>3. 若签名内容侵犯到第三方权益或涉及违禁敏感内容，将被禁用，恢复为系统默认签名。</p>
                            </div>
                            <Form>
                                <Form.Item {...formItemLayout} label="签名设置">
                                    {getFieldDecorator('sign',{
                                        rules:[{required: true, message: ' '}]
                                    })(
                                        <div>【{signName.SignName}】</div>
                                    )}
                                </Form.Item>
                                <Form.Item {...formItemLayout} label=" " colon={false}>
                                    {this.renderEdit(signName)}                          
                                </Form.Item>                          
                            </Form>
                        </div> 
                    </div>
                </Card>
            </Spin>

            <Modal
                title="修改签名"
                visible={visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                confirmLoading={loading2}
            >
                <Form>
                    <Form.Item
                        {...formItemLayout}
                        label="短信签名"
                        extra="2~12个字，过长容易导致短信通道屏蔽"
                    >
                        {getFieldDecorator('SignName', {
                            initialValue: signName.SignName,
                            rules: [
                                {required: true, message: '此项为必选项'},
                                {pattern:  /^[a-zA-Z\u4e00-\u9fa5]{2,12}$/, message:'2到12个中文或英文'},
                                {whitespace: true}
                            ],
                            validateTrigger: 'onBlur'
                        })(
                            <InputText name="name" onChange={this.onTextChange}  showtotal maxLength={12} />
                        )
                    }
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label="签名测试"
                        // extra="新签名建议先测试，确保有效性"
                    >
                        {getFieldDecorator('text', {
                        })(
                            <div>
                                <div className={styles.footerInputText}>
                                    <Input onChange={this.inputValueChange} style={{paddingRight: 104}}/>
                                    <span className={styles.input}>
                                        {!start ?(
                                        <a onClick={this.clickSedText}>发送测试短信</a>
                                        ):(
                                        <span> {wait}s 重新发送</span>
                                        )}
                                    </span>                                
                                </div>
                                {showError&&<div className={styles.phoneRerro}>请填写正确手机号</div>}
                                <div className={styles.phoneExtra}>新签名建议先测试，确保有效性</div>
                            </div>                          
                        )
                    }
                    </Form.Item>
                </Form>
            </Modal>
        </Fragment>
    );
  }
}


export default connect(({ stortMessage,global, loading }) => ({
    stortMessage,
    oemInfo: global.oemInfo,
    loading2: loading.effects['stortMessage/ChangeSignName'],
  }))(Pagination)